package javango.forms;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.inject.Injector;

public class InlineForms implements Iterable<Form> {

	private final Log log = LogFactory.getLog(InlineForms.class);
	
	protected List<Form> forms = new ArrayList<Form>();
	protected String prefix;
	Injector injector;
	
	public InlineForms(Injector injector, String prefix) {
		this.injector = injector;
		this.prefix = prefix;
	}

	public InlineForms(Injector injector, String prefix, String coreField, Class<? extends Form> formClass, Map<String, String[]> values) {
		this.injector = injector;
		int ctr = 0;
		while (values.containsKey(prefix + "[" + ctr + "]-" + coreField)) {
			String[] coreValues = values.get(prefix + "[" + ctr + "]-" + coreField);
			if (coreValues != null && coreValues.length > 0 && StringUtils.isNotBlank(coreValues[0])) {
				// create a new form for this ctr,  passing the data map and the correct prefix.
				String formPrefix = prefix + "[" + ctr + "]";
			
				Form form = injector.getInstance(formClass)
					.setPrefix(formPrefix)
					.bind(values);
				
				forms.add(form);
			}
			ctr++;
		}
	}
	
	public boolean isValid() {
		boolean isvalid = true;
		for (Form form : forms) {
			if (!form.isValid()) isvalid = false;
		}
		return isvalid;
	}
	
	public InlineForms add(Form form) {
		form.setPrefix(prefix + "[" + forms.size() + "]");
		forms.add(form);
		return this;
	}

	public Iterator<Form> iterator() {
		return forms.iterator();
	}
	
	public List<Form> getFormsList() {
		return forms;
	}
	
	public int size() {
		return forms.size();
	}
	
	
}
